<!--
/**
* Copyright (C) 2022-2023 Timber Chain Cloud (TimberCLD). All Rights Reserved.
* 
* @author: luoweijian
* @email: 807301075@qq..com
* @site: https://www.timbercld.com/
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* 
* http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
*  limitations under the License.
*/
-->
<template>
  <div>
    <el-input v-model="formData.showDeptName" :placeholder="props.placeholder" readonly @click="showDialog">
      <template #append><el-button :icon="Search" @click="showDialog"></el-button></template>
    </el-input>
    <el-input :value="props.modelValue" v-show="false"></el-input>
    <el-dialog v-model="options.visible" width="30%" draggable :modal="false" :title="props.placeholder" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form size="small" :inline="true">
        <el-form-item :label="t('keyword')">
          <el-input v-model="formData.filterValue"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="default">{{ t('query') }}</el-button>
        </el-form-item>
      </el-form>
      <el-tree
        class="filter-tree"
        :data="deptList"
        :default-expanded-keys="options.expandedKeyList"
        :props="defaultProps"
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        :highlight-current="true"
        :render-after-expand="false"
        empty-text="-- 暂无数据 --"
        node-key="id"
        ref="treeRef"
      />
      <template #footer>
        <el-button type="default" @click="cancelHandle()" size="small">{{ t('cancel') }}</el-button>
        <el-button v-if="props.query" type="info" @click="clearHandle()" size="small">{{ t('clear') }}</el-button>
        <el-button type="primary" @click="commitHandle()" size="small">{{ t('confirm') }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch, nextTick } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElMessage } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import type { ElTree } from 'element-plus';
import { systemApi } from '@/api/system';

// #region 类型
export type TreeValue = {
  pid: string;
  id: string;
  name: string;
  childern: any[];
};
interface Props {
  modelValue: string;
  deptName: string;
  query: boolean;
  placeholder: string;
}
// #endregion

// #region 属性
const props = withDefaults(defineProps<Props>(), {});
const emits = defineEmits<{
  confirm: [value: TreeValue];
}>();

const treeRef = ref<InstanceType<typeof ElTree> | null>(null);

const { t } = useI18n();
// 页面配置
const options = reactive({
  visible: false,
  expandedKeyList: ['0'],
});
// 表单数据
const formData = reactive({
  filterValue: '',
  showDeptName: '',
});

// 树状结构数据、配置
const deptList = ref([]);
const defaultProps = ref({
  children: 'children',
  label: 'name',
});
// #endregion

// #region 方法
watch([() => formData.filterValue, () => props.deptName], (val1: any) => {
  treeRef.value?.filter(val1[0]);
  formData.showDeptName = val1[1];
});

const showDialog = async () => {
  options.expandedKeyList = ['0'];
  await nextTick();
  if (treeRef.value!) {
    treeRef.value?.setCurrentKey(0);
  }
  options.visible = true;
  getDeptList(props.modelValue);
};

// 获取部门
const getDeptList = async (id: string) => {
  systemApi.getDeptList().then((res) => {
    if (res.code === 0) {
      Object.assign(deptList.value, res.data);
      nextTick(() => {
        treeRef.value?.setCurrentKey(id);
        options.expandedKeyList = [id];
      });
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const filterNode = (value: string, data: TreeValue) => {
  if (!value) return;
  return data.name.includes(value);
};

const cancelHandle = () => {
  options.visible = false;
  deptList.value.length = 0;
  formData.filterValue = '';
};

const clearHandle = () => {
  formData.showDeptName = '';
  cancelHandle();
};

// 确认选择
const commitHandle = () => {
  const node = treeRef.value?.getCurrentNode();
  if (!node) {
    ElMessage.error(t('dept.chooseerror'));
  } else {
    emits('confirm', node as TreeValue);
    formData.showDeptName = node['name'];
    cancelHandle();
  }
};
// #endregion
</script>
